import {ipcMain} from 'electron';

import operateDb from '../../boss-sqlite/bossOption.js'
// let scriptRunning = false;
// let scriptPaused = false;
// let scriptInterval = null;
// 全局参数
let allParameters = {
    scriptPaused: false,
};



const mainIpcApi = {
    registerDbOption() {
        ipcMain.handle('db-select', async (event, data) => {
            try {
                const db = await operateDb();

                let sql = `
            SELECT * FROM job_logs 
            WHERE id IN (
                SELECT MAX(id) FROM job_logs
                WHERE 1=1
        `;
                const params = [];

                const page = data.page || 1;
                const limit = data.limit || 8;

                // 构造查询条件
                const conditions = [];

                if (data.boss_name) {
                    conditions.push('boss_name LIKE ?');
                    params.push("%" + data.boss_name + "%");
                }
                if (data.user_phone) {
                    conditions.push('user_phone LIKE ?');
                    params.push("%" + data.user_phone + "%");
                }

                if (data.user_inclination) {
                    conditions.push('user_inclination LIKE ?');
                    params.push("%" + data.user_inclination + "%");
                }

                if (data.user_job_expect) {
                    conditions.push('user_job_expect LIKE ?');
                    params.push("%" + data.user_job_expect + "%");
                }

                if (data.is_delivery !== '') {
                    conditions.push('is_delivery = ?');
                    params.push(data.is_delivery);
                }

                if (data.job_title) {
                    conditions.push('job_title LIKE ?');
                    params.push("%" + data.job_title + "%");
                }

                if (data.job_detail) {
                    conditions.push('job_detail LIKE ?');
                    params.push("%" + data.job_detail + "%");
                }

                if (data.job_match !== '') {
                    conditions.push('job_match = ?');
                    params.push(data.job_match.toString());
                }

                if (data.additional_greet) {
                    conditions.push('additional_greet LIKE ?');
                    params.push("%" + data.additional_greet + "%");
                }

                if (data.city) {
                    conditions.push('city LIKE ?');
                    params.push("%" + data.city + "%");
                }

                if (data.start_time && data.end_time) {
                    conditions.push('into_time BETWEEN ? AND ?');
                    params.push(data.start_time, data.end_time);
                } else if (data.start_time) {
                    conditions.push('into_time >= ?');
                    params.push(data.start_time);
                } else if (data.end_time) {
                    conditions.push('into_time <= ?');
                    params.push(data.end_time);
                }

                if (conditions.length > 0) {
                    sql += ' AND ' + conditions.join(' AND ');
                }

                sql += `
            GROUP BY boss_name
            )
            ORDER BY into_time DESC
            LIMIT ? OFFSET ?
        `;

                // 添加分页参数
                const offset = (page - 1) * limit;
                params.push(limit, offset);

                // 执行查询操作
                const result = await db.select(sql, params);
                console.log('查询结果:', result);

                return result;
            } catch (error) {
                console.error('查询失败:', error);
                throw error;
            }
        });

        //设置所有的is_delivery为已失效
        ipcMain.handle('all-data-invalid', async (event, data) => {
            try {
                const db = await operateDb();
                // 构造更新的 SQL 语句
                const sql = `UPDATE job_logs SET is_delivery = '已失效'`;

                // 执行更新操作
                await db.update(sql);

                // 发送成功回复
                event.sender.send('all-data-invalid-reply', {success: true});
                console.log('All data updated to invalid.');
            } catch (error) {
                // 发送错误回复
                event.sender.send('all-data-invalid-reply', {error: error.message});
                console.error('Failed to update all data to invalid:', error);
            }
        });
        ipcMain.handle('db-insert', async (event, data) => {
            try {
                const db = await operateDb();

                // 构造插入的 SQL 语句
                const sql = `INSERT INTO job_logs (user_phone, user_inclination, user_job_expect, is_delivery, job_title, job_detail, job_match, additional_greet, into_time, city,boss_name) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)`;

                // 执行插入操作
                await db.insert(sql, [
                    data.user_phone,
                    data.user_inclination,
                    data.user_job_expect,
                    data.is_delivery,
                    data.job_title,
                    data.job_detail,
                    data.job_match,
                    data.additional_greet,
                    data.into_time,
                    data.city,
                    data.boss_name
                ]);

                // 发送成功回复
                event.sender.send('db-insert-reply', {success: true});
                console.log('data insert success:', data);
            } catch (error) {
                // 发送错误回复
                event.sender.send('db-insert-reply', {error: error.message});
                console.error('data insert fail:', error);
            }
        });

        // total
        ipcMain.handle('db-total', async (event, data) => {
            try {
                const db = await operateDb();

                let sql = `
            SELECT COUNT(*) AS total FROM (
                SELECT MAX(id) FROM job_logs
                WHERE 1=1
        `;
                const params = [];

                // 构造查询条件
                const conditions = [];

                if (data.user_phone) {
                    conditions.push('user_phone LIKE ?');
                    params.push("%" + data.user_phone + "%");
                }

                if (data.user_inclination) {
                    conditions.push('user_inclination LIKE ?');
                    params.push("%" + data.user_inclination + "%");
                }

                if (data.user_job_expect) {
                    conditions.push('user_job_expect LIKE ?');
                    params.push("%" + data.user_job_expect + "%");
                }

                if (data.is_delivery !== '') {
                    conditions.push('is_delivery = ?');
                    params.push(data.is_delivery);
                }

                if (data.job_title) {
                    conditions.push('job_title LIKE ?');
                    params.push("%" + data.job_title + "%");
                }

                if (data.job_detail) {
                    conditions.push('job_detail LIKE ?');
                    params.push("%" + data.job_detail + "%");
                }

                if (data.job_match !== '') {
                    conditions.push('job_match = ?');
                    params.push(data.job_match.toString());
                }

                if (data.additional_greet) {
                    conditions.push('additional_greet LIKE ?');
                    params.push("%" + data.additional_greet + "%");
                }

                if (data.city) {
                    conditions.push('city LIKE ?');
                    params.push("%" + data.city + "%");
                }

                if (data.start_time && data.end_time) {
                    conditions.push('into_time BETWEEN ? AND ?');
                    params.push(data.start_time, data.end_time);
                } else if (data.start_time) {
                    conditions.push('into_time >= ?');
                    params.push(data.start_time);
                } else if (data.end_time) {
                    conditions.push('into_time <= ?');
                    params.push(data.end_time);
                }

                if (conditions.length > 0) {
                    sql += ' AND ' + conditions.join(' AND ');
                }

                sql += `
            GROUP BY boss_name
            ) AS latest_records
        `;

                // 执行查询操作
                const result = await db.select(sql, params);
                const total = result[0]?.total || 0;
                console.log('总数:', total);

                return total;
            } catch (error) {
                console.error('查询失败:', error);
                throw error;
            }
        });

        //dbDelete
        ipcMain.handle('db-delete', async (event, data) => {
            try {
                const db = await operateDb(); // 获取数据库实例，假设 operateDb 返回一个 SQLite 数据库实例

                // 验证是否传入了要删除的 id 数组
                if (!data.ids || !Array.isArray(data.ids) || data.ids.length === 0) {
                    return
                }

                // 构造批量删除 SQL 语句
                const placeholders = data.ids.map(() => '?').join(', ');
                const sql = `DELETE FROM job_logs WHERE id IN (${placeholders})`;

                // 执行批量删除操作
                await db.remove(sql, data.ids);

                console.log(`成功删除 ${data.ids.length} 条记录`);

                // 发送成功回复
                event.sender.send('db-delete-reply', {success: true});
            } catch (error) {
                console.error('删除失败:', error);

                // 发送错误回复
                event.sender.send('db-delete-reply', {error: error.message});
            }
        });

        //deleteAll 一键清除
        ipcMain.handle('db-delete-all', async (event, _) => {
            try {
                const db = await operateDb(); // 获取数据库实例，假设 operateDb 返回一个 SQLite 数据库实例

                // 构造删除所有记录的 SQL 语句
                const sql = `DELETE FROM job_logs`;

                // 执行删除所有记录操作
                await db.remove(sql);

                console.log('成功删除所有记录');

                // 发送成功回复
                event.sender.send('db-delete-all-reply', { success: true });
            } catch (error) {
                console.error('删除所有记录失败:', error);

                // 发送错误回复
                event.sender.send('db-delete-all-reply', { error: error.message });
            }
        });

        //     插入用户的行为操作
        ipcMain.handle('db-job-form-insert', async (event, data) => {
            const jsonData = JSON.parse(data)
            console.log('打印传递的数据', jsonData)
            try {
                const db = await operateDb();

                // 构造插入的 SQL 语句
                const sql = `
            INSERT INTO job_form (
                city, job_type, salary, job_year, educational,
                industry, company_scale, like_job, analysis_detail,
                job_keywords, user_job_expect
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `;

                // 执行插入操作
                await db.insert(sql, [
                    jsonData.city,
                    jsonData.job_type,
                    jsonData.salary,
                    jsonData.job_year,
                    jsonData.educational,
                    jsonData.industry,
                    jsonData.company_scale,
                    jsonData.like_job,
                    jsonData.analysis_detail,
                    JSON.stringify(jsonData.job_keywords), // 将数组转换为字符串存储
                    jsonData.user_job_expect
                ]);

                // 发送成功回复
                event.sender.send('db-job-form-insert-reply', {success: true});
                console.log('Form data insert success:', data);
            } catch (error) {
                // 发送错误回复
                event.sender.send('db-job-form-insert-reply', {error: error.message});
                console.error('Form data insert fail:', error);
            }
        });

        //     查询用户信息
        ipcMain.handle('db-job-form-select', async (event, data) => {
            try {
                const jsonData = JSON.parse(data);
                console.log('打印传递的数据', jsonData);

                const db = await operateDb();

                let sql = 'SELECT * FROM job_form';
                const params = [];

                // 构造查询条件
                if (jsonData) {
                    const conditions = [];

                    if (jsonData.city) {
                        conditions.push('city = ?');
                        params.push(jsonData.city);
                    }

                    if (jsonData.job_type) {
                        conditions.push('job_type = ?');
                        params.push(jsonData.job_type);
                    }

                    if (jsonData.salary) {
                        conditions.push('salary = ?');
                        params.push(jsonData.salary);
                    }

                    if (jsonData.job_year) {
                        conditions.push('job_year = ?');
                        params.push(jsonData.job_year);
                    }

                    if (jsonData.educational) {
                        conditions.push('educational = ?');
                        params.push(jsonData.educational);
                    }

                    if (jsonData.industry) {
                        conditions.push('industry = ?');
                        params.push(jsonData.industry);
                    }

                    if (jsonData.company_scale) {
                        conditions.push('company_scale = ?');
                        params.push(jsonData.company_scale);
                    }

                    if (jsonData.like_job) {
                        conditions.push('like_job = ?');
                        params.push(jsonData.like_job);
                    }

                    if (jsonData.analysis_detail) {
                        conditions.push('analysis_detail = ?');
                        params.push(jsonData.analysis_detail);
                    }

                    if (jsonData.user_job_expect) {
                        conditions.push('user_job_expect = ?');
                        params.push(jsonData.user_job_expect);
                    }

                    if (conditions.length > 0) {
                        sql += ' WHERE ' + conditions.join(' AND ');
                    }
                }

                // 按时间排序，最新的在前面
                sql += ' ORDER BY created_time DESC';

                // 只查询前十五条
                sql += ' LIMIT 15';

                // 执行查询操作
                const result = await db.select(sql, params);

                console.log('查询结果:', result);

                return result;
            } catch (error) {
                console.error('查询失败:', error);
                throw error;
            }
        });

    //     获取全局参数
        ipcMain.handle('get-all-Parameters',async (event,_)=>{
            return
        })

        // 新增的四个 ipcMain.handle 方法
        ipcMain.handle('db-user-config-select', async (event, data) => {
            try {
                const db = await operateDb();

                let sql = `
            SELECT * FROM user_config
            WHERE 1=1
        `;
                const params = [];

                // 构造查询条件
                const conditions = [];

                if (data.id) {
                    conditions.push('id = ?');
                    params.push(data.id);
                }
                if (data.is_greet !== '') {
                    conditions.push('is_greet = ?');
                    params.push(data.is_greet);
                }
                if (data.user_key) {
                    conditions.push('user_key LIKE ?');
                    params.push("%" + data.user_key + "%");
                }

                if (conditions.length > 0) {
                    sql += ' AND ' + conditions.join(' AND ');
                }

                // 执行查询操作
                const result = await db.select(sql, params);
                console.log('查询结果:', result);

                return result;
            } catch (error) {
                console.error('查询失败:', error);
                throw error;
            }
        });

        ipcMain.handle('db-user-config-delete', async (event, data) => {
            try {
                const db = await operateDb();

                let sql = `
            DELETE FROM user_config
            WHERE 1=1
        `;
                const params = [];

                // 构造删除条件
                const conditions = [];

                if (data.id) {
                    conditions.push('id = ?');
                    params.push(data.id);
                }
                if (data.is_greet !== '') {
                    conditions.push('is_greet = ?');
                    params.push(data.is_greet);
                }
                if (data.user_key) {
                    conditions.push('user_key LIKE ?');
                    params.push("%" + data.user_key + "%");
                }

                if (conditions.length > 0) {
                    sql += ' AND ' + conditions.join(' AND ');
                }

                // 执行删除操作
                await db.remove(sql, params);
                console.log('删除成功');
                event.sender.send('db-user-config-delete-reply', { success: true });
            } catch (error) {
                console.error('删除失败:', error);
                event.sender.send('db-user-config-delete-reply', { error: error.message });
            }
        });

        ipcMain.handle('db-user-config-update', async (event, data) => {
            try {
                const db = await operateDb();

                let sql = `UPDATE user_config SET `;
                const updateParams = [];
                const conditionParams = [];

                // 构造更新字段
                const updateFields = [];
                for (const key in data.values) {
                    updateFields.push(`${key} = ?`);
                    updateParams.push(data.values[key]);
                }

                sql += updateFields.join(', ');

                // 构造更新条件
                const conditions = [];
                if (data.condition.id) {
                    conditions.push('id = ?');
                    conditionParams.push(data.condition.id);
                }
                if (data.condition.is_greet !== '') {
                    conditions.push('is_greet = ?');
                    conditionParams.push(data.condition.is_greet);
                }
                if (data.condition.user_key) {
                    conditions.push('user_key LIKE ?');
                    conditionParams.push("%" + data.condition.user_key + "%");
                }

                if (conditions.length > 0) {
                    sql += ' WHERE ' + conditions.join(' AND ');
                }

                // 执行更新操作
                await db.update(sql, [...updateParams, ...conditionParams]);
                console.log('更新成功');
                event.sender.send('db-user-config-update-reply', { success: true });
            } catch (error) {
                console.error('更新失败:', error);
                event.sender.send('db-user-config-update-reply', { error: error.message });
            }
        });

        ipcMain.handle('db-user-config-insert', async (event, data) => {
            try {
                const db = await operateDb();

                const sql = `INSERT INTO user_config (id, is_greet, user_key) VALUES (?, ?, ?)`;

                // 执行插入操作
                await db.insert(sql, [
                    data.id,
                    data.is_greet,
                    data.user_key
                ]);
                console.log('插入成功');
                event.sender.send('db-user-config-insert-reply', { success: true });
            } catch (error) {
                console.error('插入失败:', error);
                event.sender.send('db-user-config-insert-reply', { error: error.message });
            }
        });
    },
//     注册生命周期组件
    registerLifeCycleOption() {
        ipcMain.handle('pause-script', (event,data:boolean) => {
            if (data == null){
                return allParameters.scriptPaused
            }
            allParameters.scriptPaused = data
            return  allParameters.scriptPaused
        });

    }
}


export default mainIpcApi;
